import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { ComponentType } from 'react';

export default function withAuth<P extends object>(
  WrappedComponent: ComponentType<P>,
  allowedRoles: string[] = []
) {
  return (props: P) => {
    const Router = useRouter();
    const [authorized, setAuthorized] = useState(false);

    useEffect(() => {
      const checkAuth = async () => {
        const token = localStorage.getItem('token');
        const userRole = localStorage.getItem('userRole');

        if (!token) {
          Router.push('/login');
        } else if (allowedRoles.length > 0 && userRole && !allowedRoles.includes(userRole)) {
          Router.push('/403');
        } else {
          setAuthorized(true);
        }
      };

      checkAuth();
    }, []);

    if (authorized) {
      return <WrappedComponent {...props} />;
    } else {
      return null;
    }
  };
}